﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ViewWindow.Config;
using 视觉框架测试.Tool;

namespace 视觉框架测试.Tool
{
    [Serializable]
    public class Tool_ShapeMatching : BaseTool
    {
        //[NonSerialized]
        public Tool_ShapeMatching()
        {
            Tool_Type = typeof(Tool_ShapeMatching);
            //Tool_guid = Guid.NewGuid();
            ini();
        }

        public HShapeModel Shape_Model = new HShapeModel();
        public override void ini()
        {
            //Region = new ViewWindow.Model.ROI();
            Search_Region = new Rectangle2();

        }
        public void Create_shapeModel()
        {
            HOperatorSet.GenRectangle2(out HObject rect2, Search_Region.Row, Search_Region.Column, Search_Region.Phi, Search_Region.Lenth1, Search_Region.Lenth2);
            HOperatorSet.ReduceDomain(Image, rect2, out HObject imageReduce);
            //创建形状模版
            HImage hImage = new HImage(imageReduce);
            Shape_Model.CreateShapeModel(hImage, "auto", (new HTuple(-20)).TupleRad(), (new HTuple(40)).TupleRad(), "auto", "auto", "ignore_local_polarity", "auto", "auto");
            //HOperatorSet.CreateShapeModel(imageReduce, "auto", (new HTuple(-20)).TupleRad(), (new HTuple(40)).TupleRad(), "auto", "auto", "ignore_local_polarity", "auto", "auto", out Shape_Model);

        }

        public override BaseTool Run(BaseTool baseTool)
        {
            //记录程序运行时间
            Stopwatch sw = new Stopwatch();
            sw.Start();
            BaseTool DeepCopy_Tool = DeepCopy(baseTool);
            if (Shape_Model != null)
            {
                //在给定的图中查找模板
                HOperatorSet.FindShapeModel(baseTool.Image, Shape_Model, (new HTuple(-20)).TupleRad(), (new HTuple(40)).TupleRad(), 0.5, 1, 0.0, "least_squares", 2, 0.9, out HTuple hv_Row, out HTuple hv_Column, out HTuple hv_Angle, out HTuple hv_Score);
                if (hv_Score.D > 0.5)
                {
                    DeepCopy_Tool.Row = hv_Row;
                    DeepCopy_Tool.Column = hv_Column;
                    DeepCopy_Tool.Angle = hv_Angle;
                    DeepCopy_Tool.Score = hv_Score;
                    DeepCopy_Tool.IsOK = true;
                }
                else
                {
                    DeepCopy_Tool.IsOK = false;
                }

            }
            sw.Stop();
            DeepCopy_Tool.Image = baseTool.Image;
            DeepCopy_Tool.Search_Region = Search_Region;
            DeepCopy_Tool.ConsumeTime = sw.ElapsedMilliseconds;
            DeepCopy_Tool.OutputNode_guid = OutputNode_guid;
            DeepCopy_Tool.STN_guid = STN_guid;
            return DeepCopy_Tool;
        }
    }
}
